package oop.controller.action.user;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;

import oop.data.User;
import oop.db.Database;
import oop.db.dao.UserDAO;

import org.apache.commons.lang.StringEscapeUtils;

public class EditUserAction extends UserManagerAction {

	@Override
	public void performImpl() throws Exception {


		User user = (User) request.getSession().getAttribute("user");
		request.setAttribute("userName", user.getName());
		request.setAttribute("userCurrEmail", user.getEmail());
		request.setAttribute("userFullName", user.getFullname());
		title("Thay đổi thông tin cá nhân của " + user.getName());
		if ("Change".equals(request.getParameter("change"))) {
			int errorEmail = updateEmail();
			int errorPass = updatePass();
			int error = 0;
			// if ((errorEmail == 0)&&(errorPass == 0));
			if (errorEmail == -1) {
				request.setAttribute("invalidEmail", "true");
				error++;
			} else if (errorEmail == -2) {
				request.setAttribute("emailUnavailable", "true");
				error++;
			} else if (errorEmail == -3) {
				request.setAttribute("dbError", "true");
				error++;
			}
			if ((errorPass == -1) || (errorPass == -3)) {
				request.setAttribute("wrongPass", "true");
				error++;
			} else if (errorPass == -2) {
				request.setAttribute("invalidPass", "true");
				error++;
			} else if (errorPass == -4) {
				request.setAttribute("dbError", "true");
				error++;
			}
			if (((errorEmail >= 0) && (errorPass >= 0))
					&& ((errorEmail != 0) || (errorPass != 0)))
				request.setAttribute("success", "true");
				user = UserDAO.fetchByUsername(getUser().getName()).get(0);
				request.getSession().setAttribute("user", user);
			if (error > 0)
				request.setAttribute("error", "true");
		}

	}

/*	public boolean getUserInfo(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			SQLException {
		User user = (User) request.getSession(true).getAttribute("user");

		if (userName == null)
			return false;
		Connection conn;
		try {
			conn = Database.get().getConnection();
			Statement stmt = conn.createStatement();
			String sql = "SELECT user_name, user_email, user_fullname "
					+ "FROM tblUser " + "WHERE user_name = '" + userName + "'";
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				request.setAttribute("userCurrEmail", rs
						.getString("user_email"));
				request.setAttribute("userFullName", rs
						.getString("user_fullname"));
				return true;
			} else
				return false;

		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	*/

	private int updateEmail() throws ServletException, IOException, SQLException {

		String email = request.getParameter("userEmail");
		email = StringEscapeUtils.escapeSql(email);
		if (isEmpty(email))
			return 0;
		if (isValidEmail() == false) {
			return -1;
		} else {
			if (isEmailExist()) {
				return -2;
			}
			Connection conn = null;
			Statement stmt = null;
			try {
				conn = Database.get().getConnection();
				stmt = conn.createStatement();
				String uName = getUser().getName();
				String sql = "UPDATE `tracnghiem`.`tblUser` SET `user_email` = '"
						+ email
						+ "' WHERE `tblUser`.`user_name` ='"
						+ uName + "'";
				stmt.executeUpdate(sql);
				return 1;
			} catch (SQLException e) {

				e.printStackTrace();
				return -3;
			} finally {
				if (stmt != null) stmt.close();
				if (conn != null) conn.close();
			}
		}
	}

	private int updatePass() throws ServletException, IOException, SQLException {
		String pass = request.getParameter("password");
		pass = StringEscapeUtils.escapeSql(pass);
		String changedPass = request.getParameter("changedPassword");
		changedPass = StringEscapeUtils.escapeSql(changedPass);
		String confirmPass = request.getParameter("confirmPass");
		confirmPass = StringEscapeUtils.escapeSql(confirmPass);
		String passOnSql = null;
		if ((isEmpty(pass)) && (isEmpty(changedPass)) && (isEmpty(confirmPass)))
			return 0;
		passOnSql = getUserPassOnSQL(getUser().getName());
		if (passOnSql == null)
			return -3;
		else if (pass.compareTo(passOnSql) != 0)
			return -1;
		else if (isValidPassword() == false)
			return -2;
		else {
			Connection conn = null;
			Statement stmt = null;
			try {
				conn = Database.get().getConnection();
				stmt = conn.createStatement();
				String uName = getUser().getName();
				String sql = "UPDATE `tracnghiem`.`tblUser` SET `user_pass` = '"
						+ changedPass
						+ "' WHERE `tblUser`.`user_name` ='"
						+ uName + "'";
				stmt.executeUpdate(sql);
				return 1;
			} catch (SQLException e) {

				e.printStackTrace();
				return -4;
			} finally {
				if (stmt != null) stmt.close();
				if (conn != null) conn.close();
			}
		}

	}

	private boolean isValidPassword() throws ServletException, IOException {
		String pass = request.getParameter("changedPassword");
		String confPass = request.getParameter("confirmPass");
		if ((pass.compareTo(confPass) != 0) || (isEmpty(pass)))
			return false;
		return true;
	}
}
